package com.dhl.fin.api.service;

import com.dhl.fin.api.common.dto.QueryDto;
import com.dhl.fin.api.common.service.CommonService;
import com.dhl.fin.api.common.util.ObjectUtil;
import com.dhl.fin.api.common.util.StringUtil;
import com.dhl.fin.api.common.util.WebUtil;
import com.dhl.fin.api.domain.Consult;
import com.dhl.fin.api.domain.ConsultChat;
import com.dhl.fin.api.domain.Family;
import com.dhl.fin.api.enums.ConsultChatStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author CuiJianbo
 * @since 2025/3/16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ConsultService extends CommonService<Consult> {

    @Autowired
    private ConsultChatService consultChatService;

    @Autowired
    private FamilyService familyService;

    @Override
    public void beforeSave(Consult domain) throws Exception {
        domain.setWxAccountCode(WebUtil.getLoginUser().getUuid());
        domain.setReplyStatus(ConsultChatStatusEnum.WAIT_REPLY.getCode());
    }

    @Override
    public void afterSave(Consult domain) throws Exception {
        Family family = familyService.getLoginUserInfo();
        ConsultChat consult = new ConsultChat();
        consult.setConsult(domain);
        consult.setContent(domain.getContent());
        consult.setOwner(WebUtil.getLoginUser().getUuid());
        consult.setOwnerHead(family.getHeadPicPath());
        consultChatService.save(consult);

    }

    public Boolean hasConsult() throws Exception {
        String unicode = WebUtil.getStringParam("unicode");
        if (StringUtil.isNotEmpty(unicode)) {
            Consult consult = get(QueryDto.builder()
                    .available()
                    .addWhere("family_unicode='" + unicode + "'")
                    .build());
            return ObjectUtil.notNull(consult);
        } else {
            return false;
        }
    }

    public Boolean hasReplyConsult() throws Exception {
        String unicode = WebUtil.getStringParam("unicode");
        if (StringUtil.isNotEmpty(unicode)) {
            Consult consult = get(QueryDto.builder()
                    .available()
                    .addWhere("family_unicode='" + unicode + "'")
                    .addWhere("reply_status = '" + ConsultChatStatusEnum.REPLIED.getCode() + "'")
                    .build());
            return ObjectUtil.notNull(consult);
        } else {
            return false;
        }
    }


    public void setConsultViewed(Long id) throws Exception {
        updateFieldById(id, "replyStatus", ConsultChatStatusEnum.VIEWED.getCode());
    }

}
